package com.qimei.onerice.servlet;

import com.google.gson.Gson;
import com.qimei.onerice.entity.Dish;
import com.qimei.onerice.entity.Order;
import com.qimei.onerice.entity.OrderDetail;
import com.qimei.onerice.service.OrderService;
import com.qimei.onerice.service.impl.DishServiceImpl;
import com.qimei.onerice.service.impl.OrderDetailServiceImpl;
import com.qimei.onerice.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

@WebServlet("/order")
public class OrderServlet extends HttpServlet {
	OrderService orderService = new OrderServiceImpl();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");

		String action = request.getParameter("action");

		if ("getAll".equals(action)) {
			// 获取所有订单数据
			handleGetList(request, response);
		} else if ("getById".equals(action)) {
			// 获取单个订单数据
			handleGetById(request, response);
		} else if ("add".equals(action)) {
			// 添加订单
			handleAdd(request, response);
		} else if ("checkout".equals(action)) {
			// 添加订单
			handleCheckOut(request, response);
		} else {
			// 未知的操作类型
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			response.getWriter().println("未知的操作");
		}
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String action = request.getParameter("action");

		System.out.println(action);
		if ("update".equals(action)) {
			// 更新订单
			handleUpdate(request, response);
		} else if ("delete".equals(action)) {
			// 删除订单
			handleDelete(request, response);
		} else {
			// 未知的操作类型
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			response.getWriter().println("未知操作");
		}
	}
	// 添加新订单
	private void handleAdd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// 从请求中提取参数
		String customerId = request.getParameter("customerId");
		String dishId = request.getParameter("dishId");

		Order currentOrder = new OrderServiceImpl().getCurrentOrder();
		Dish dish = new DishServiceImpl().getDishById(Integer.parseInt(dishId));

		// 判断当前是否有购物车
		if ( currentOrder == null ) {
			// 购物车为空创建一个新的购物车
			Order newOrder = new Order();
			newOrder.setOrderStatus("未支付");
			newOrder.setOrderTime(new Date());
			newOrder.setCustomerId(Integer.parseInt(customerId));
			newOrder.setTotalAmount(dish.getPrice());
			boolean success = orderService.addOrder(newOrder);

			Order order = new OrderServiceImpl().getCurrentOrder();
			OrderDetail newOrderTail = new OrderDetail();
			newOrderTail.setOrderId(order.getOrderId());
			newOrderTail.setDishId(dish.getDishId());
			newOrderTail.setQuantity(1);
			newOrderTail.setUnitPrice(dish.getPrice());
			newOrderTail.setSubtotal(1 * dish.getPrice());
			boolean success2 = new OrderDetailServiceImpl().addOrderDetail(newOrderTail);

			// 获取更新后的购物车信息并返回
			Order orderById = new OrderServiceImpl().getOrderById(order.getOrderId());
			HttpSession session = request.getSession();
			session.setAttribute("order", orderById);
			session.setAttribute("message", "添加成功");
			// 请求转发至JSP页面展示信息更新结果
			request.getRequestDispatcher("/view/store.jsp").forward(request, response);
		} else {
			// 购物车已经存在
			OrderDetail orderDetailByDishId = new OrderDetailServiceImpl().getOrderDetailByDishId(currentOrder.getOrderId(), Integer.parseInt(dishId));
			if (orderDetailByDishId != null) {
				// 当前菜品已经存在
				orderDetailByDishId.setQuantity(orderDetailByDishId.getQuantity() + 1);
				orderDetailByDishId.setSubtotal(orderDetailByDishId.getQuantity() * orderDetailByDishId.getUnitPrice());
				boolean success = new OrderDetailServiceImpl().updateOrderDetail(orderDetailByDishId);
				currentOrder.setTotalAmount(currentOrder.getTotalAmount() + orderDetailByDishId.getUnitPrice());
				boolean success2 = new OrderServiceImpl().updateOrder(currentOrder);
			} else {
				// 当前菜品不存在
				OrderDetail newOrderTail = new OrderDetail();
				newOrderTail.setOrderId(currentOrder.getOrderId());
				newOrderTail.setDishId(dish.getDishId());
				newOrderTail.setQuantity(1);
				newOrderTail.setUnitPrice(dish.getPrice());
				newOrderTail.setSubtotal(1 * dish.getPrice());
				boolean success2 = new OrderDetailServiceImpl().addOrderDetail(newOrderTail);
				currentOrder.setTotalAmount(currentOrder.getTotalAmount() + dish.getPrice());
				boolean success3 = new OrderServiceImpl().updateOrder(currentOrder);
			}
			// 获取更新后的购物车信息并返回
			Order orderById = new OrderServiceImpl().getOrderById(currentOrder.getOrderId());
			HttpSession session = request.getSession();
			session.setAttribute("order", orderById);
			session.setAttribute("message", "添加成功");
			// 请求转发至JSP页面展示信息更新结果
			request.getRequestDispatcher("/view/store.jsp").forward(request, response);
		}

	}

	// 更新订单
	private void handleUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 从请求中提取参数
//		String orderIdParam = request.getParameter("orderId");
//		int orderId = Integer.parseInt(orderIdParam);
//		String orderName = request.getParameter("orderName");
//		String orderUserName = request.getParameter("orderUsername");
//		String orderEmail = request.getParameter("orderEmail");
//		String orderPhone = request.getParameter("orderPhone");
//
//		Order updatedOrder = new Order();
//		updatedOrder.setOrderId(orderId);
//		updatedOrder.setOrderName(orderName);
//		updatedOrder.setOrderUsername(orderUserName);
//		updatedOrder.setOrderEmail(orderEmail);
//		updatedOrder.setOrderPhone(orderPhone);
//
//		System.out.println(updatedOrder);
//		// 调用服务方法更新订单
//		boolean success = orderService.updateOrder(updatedOrder);
//		// 发送响应
//		sendJsonResponse(response, "{\"success\":" + success + "}");
	}

	// 删除订单
	private void handleDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 从请求中提取参数
		String orderId = request.getParameter("orderId");

		// 调用服务方法删除订单
		boolean success = orderService.deleteOrder(Integer.parseInt(orderId));

		// 发送响应
		sendJsonResponse(response, "{\"success\":" + success + "}");
	}
	// 结账
	private void handleCheckOut(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// 从请求中提取参数
		String orderId = request.getParameter("orderId");

		// 调用服务方法
		Order order = orderService.getOrderById(Integer.parseInt(orderId));
		order.setOrderStatus("已结账");
		orderService.updateOrder(order);

		request.getSession().removeAttribute("order");

		request.getRequestDispatcher("/view/store.jsp").forward(request, response);
	}

	// 根据ID查询订单
	private void handleGetById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 从请求中提取参数
		String orderIdParam = request.getParameter("orderId");

		int orderId = Integer.parseInt(orderIdParam);

		// 调用方法根据ID获取订单
		Order order = orderService.getOrderById(orderId);

		// 将 Order 对象转换为 JSON 并发送响应
		String jsonData = new Gson().toJson(order);
		sendJsonResponse(response, jsonData);
	}


	private void handleGetList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Order> orderList = orderService.getOrderList();
		// 将 Order 对象转换为 JSON 并发送响应
		String jsonData = new Gson().toJson(orderList);
		sendJsonResponse(response, jsonData);
	}

	private void sendJsonResponse(HttpServletResponse response, String jsonData) throws IOException {
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(jsonData);
		out.flush();
	}
}
